#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import json


import initAlipayPage
from data_alchemy.alipay_bill_aclchemy import AlipayBillAlchemy
from data_alchemy.alipay_bill_new_alchemy import AlipayBillNewAlchemy
from data_alchemy.alipay_voucher_alchemy import AlipayVoucherAlchemy
from data_alchemy.alipay_voucher_preview_alchemy import AlipayVoucherPreviewAlchemy
from data_alchemy.bill_parse_regulation_alchemy import BillParseRegulationAlchemy
from initBillParseDialog import BILL_TYPE_LIST
from initLogger import logger
from toolkit import setLastDayOfMonth


class AutoParseBill:

    def __init__(self):
        '''
        函数功能：构造函数
        '''

        self.billParseRules = None  #账单解析规则
        self.alipayBillAlchemy =None  # 老账单数据库表类对象，不再使用
        self.alipayBillAlchemy = None   # 账单数据库表类对象
        self.alipayBillInforList = None #支付宝账单信息列表

        self.year=0
        self.month=0

    def alipayBillToAccountVoucher(self, year, month):
        '''
        函数功能：将支付宝账单转化为记账凭证
        :param year:
        :param month:
        :return:
        '''
        logger.debug("call alipayBillToAccountVoucher function")
        self.loadParseBillRules()  #加载账单解析规则
        self.loadAlipayBillData(year, month)  #加载支付宝账单信息列表
        self.year = year
        self.month = month

        for billRuleItem in self.billParseRules:
            regulationItemDic = json.loads(billRuleItem.regulation)
            logger.debug(regulationItemDic)
            self.processOneBillRuleItem(billRuleItem)

    def alipayNewBillToAccountVoucher(self, year, month):
        '''
        函数功能：将支付宝账单转化为记账凭证
        :param year:
        :param month:
        :return:
        '''
        logger.debug("call alipayBillToAccountVoucher function")
        self.loadParseBillRules()  #加载账单解析规则
        self.loadNewAlipayBillData(year, month)  #加载支付宝账单信息列表
        self.year = year
        self.month = month

        for billRuleItem in self.billParseRules:
            regulationItemDic = json.loads(billRuleItem.regulation)
            logger.debug(regulationItemDic)

            self.processNewOneBillRuleItem(billRuleItem)


    def processOneBillRuleItem(self, billRuleItem):
        '''
        函数功能：用一条账单规则来匹配目标账单
        :param billRuleItem:
        :return:
        '''
        logger.debug("call processOneBillRuleItem function")
        regulationDic = json.loads(billRuleItem.regulation)  #把字符串形式的规则解析为json结构的字典
        logger.debug(regulationDic)
        matchFlag=False   #判断是否与规则匹配
        matchBillList=[]

        for billItem in self.alipayBillInforList:

            if billItem.matched == True:
                continue

            matchFlag=True #设置为匹配
            logger.debug(billItem)
            for regulationKeyItem in regulationDic.keys():
                logger.debug(regulationKeyItem)
                BillItemAttrValue = getattr(billItem, regulationKeyItem, None)

                if BillItemAttrValue != regulationDic.get(regulationKeyItem):
                    #当前账单与规则不匹配
                    matchFlag=False
                    break

            #end for regulationKeyItem
            if matchFlag==True:
                #把匹配规则的账单，添加入matchBillList
                billItem.matched = True
                billItem.bill_type= initAlipayPage.NORMAL_BILL_TYPE
                matchBillList.append(billItem)
            else:
                billItem.matched = False
                billItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE

        # end for billItem
        logger.debug(matchBillList)

        #self.addVoucherFromBill(billRuleItem, matchBillList)
        if len(matchBillList)==0:
            #没有匹配到账单
            return

        if billRuleItem.is_merge == True:
            self.mergeAddVoucherFromBill(billRuleItem, matchBillList)
        else:
            self.addVoucherFromBill(billRuleItem, matchBillList)
        return

    def processNewOneBillRuleItem(self, billRuleItem):
        '''
        函数功能：用一条账单规则来匹配目标账单
        :param billRuleItem:
        :return:
        '''
        logger.debug("call processOneBillRuleItem function")
        regulationDic = json.loads(billRuleItem.regulation)  #把字符串形式的规则解析为json结构的字典
        logger.debug(regulationDic)
        matchFlag=False   #判断是否与规则匹配
        matchBillList=[]

        if billRuleItem.is_valid==False:
            pass

        for billItem in self.alipayBillInforList:

            '''
            if (billItem.trade_order_no_first=="2024022522001196501435374370" and \
                billRuleItem.id==10):
                #用于排查异常账单，排错
                pass
                print("ddddd")
            '''

            if billItem.matched == True:
                continue

            matchFlag=True #设置为匹配
            logger.debug(billItem)
            for regulationKeyItem in regulationDic.keys():
                logger.debug(regulationKeyItem)
                BillItemAttrValue = getattr(billItem, regulationKeyItem, None)

                if BillItemAttrValue != regulationDic.get(regulationKeyItem):
                    #当前账单与规则不匹配
                    matchFlag=False
                    break

            #end for regulationKeyItem

            if matchFlag==True and billRuleItem.is_valid==True:
                #把匹配规则的账单，且匹配该规则的账单是一个有效账单，添加入matchBillList
                billItem.matched = True
                billItem.bill_type=initAlipayPage.NORMAL_BILL_TYPE
                matchBillList.append(billItem)
            elif matchFlag==True and billRuleItem.is_valid==False:
                # 把匹配规则的账单，且匹配该规则的账单是一个无效账单，
                billItem.matched = True
                billItem.bill_type = initAlipayPage.INVALID_BILL_TYPE
                #matchBillList.append(billItem)

            else:
                billItem.matched = False
                billItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE

        # end for billItem
        logger.debug(matchBillList)

        #self.addVoucherFromBill(billRuleItem, matchBillList)
        self.alipayBillNewAlchemy.CommitData()

        if len(matchBillList)==0:
            #没有匹配到账单
            return
        

        if billRuleItem.is_merge == True:
            self.mergeAddVoucherFromNewBill(billRuleItem, matchBillList)
        else:
            self.addVoucherFromNewBill(billRuleItem, matchBillList)
            

        return

    def addVoucherFromBill(self, billRuleItem, matchBillList):
        '''
        函数功能：将匹配规则的账单分别添加到preview记账凭证标中
        :param billRuleItem:
        :param matchBillList:
        :return:
        '''

        for matchBillListItem in matchBillList:

            if billRuleItem.property_increame_name == "":
                propertyIncreaseValue = 0.0
            else:
                propertyIncreaseValue = matchBillListItem.value

            if billRuleItem.property_decrease_name == "":
                propertyDecreaseValue = 0.0
            else:
                propertyDecreaseValue = matchBillListItem.value

            if billRuleItem.ownership_increase_name == "":
                ownershipIncreaseValue = 0.0
            else:
                ownershipIncreaseValue = matchBillListItem.value

            if billRuleItem.ownership_decrease_name == "":
                ownershipDecreaseValue = 0.0
            else:
                ownershipDecreaseValue =matchBillListItem.value


            accountVoucher = AlipayVoucherPreviewAlchemy(matchBillListItem.trade_time,
                                                     voucherNo="000",
                                                     summary=billRuleItem.summary,
                                                     propertyIncreaseName=billRuleItem.property_increame_name,
                                                     propertyIncreaseValue=propertyIncreaseValue,
                                                     propertyDecreaseName=billRuleItem.property_decrease_name,
                                                     propertyDecreaseValue=propertyDecreaseValue,
                                                     ownershipIncreaseName=billRuleItem.ownership_increase_name,
                                                     ownershipIncreaseValue=ownershipIncreaseValue,
                                                     ownershipDecreaseName=billRuleItem.ownership_decrease_name,
                                                     ownershipDecreaseValue=ownershipDecreaseValue,
                                                     voucherType=""
                                                     )

            accountVoucher.AddVoucherItem()
            accountVoucher.CommitVoucherData()


    def addVoucherFromNewBill(self, billRuleItem, matchBillList):
        '''
        函数功能：将匹配规则的账单分别添加到preview记账凭证标中
        :param billRuleItem:
        :param matchBillList:
        :return:
        '''

        for matchBillListItem in matchBillList:

            if billRuleItem.property_increame_name == "":
                propertyIncreaseValue = 0.0
            else:
                propertyIncreaseValue = matchBillListItem.value_first

            if billRuleItem.property_decrease_name == "":
                propertyDecreaseValue = 0.0
            else:
                propertyDecreaseValue = matchBillListItem.value_first

            if billRuleItem.ownership_increase_name == "":
                ownershipIncreaseValue = 0.0
            else:
                ownershipIncreaseValue = matchBillListItem.value_first

            if billRuleItem.ownership_decrease_name == "":
                ownershipDecreaseValue = 0.0
            else:
                ownershipDecreaseValue =matchBillListItem.value_first


            accountVoucher = AlipayVoucherPreviewAlchemy(matchBillListItem.settlement_time,
                                                     voucherNo="000",
                                                     summary=billRuleItem.summary,
                                                     propertyIncreaseName=billRuleItem.property_increame_name,
                                                     propertyIncreaseValue=propertyIncreaseValue,
                                                     propertyDecreaseName=billRuleItem.property_decrease_name,
                                                     propertyDecreaseValue=propertyDecreaseValue,
                                                     ownershipIncreaseName=billRuleItem.ownership_increase_name,
                                                     ownershipIncreaseValue=ownershipIncreaseValue,
                                                     ownershipDecreaseName=billRuleItem.ownership_decrease_name,
                                                     ownershipDecreaseValue=ownershipDecreaseValue,
                                                     voucherType=""
                                                     )

            accountVoucher.AddVoucherItem()
            accountVoucher.CommitVoucherData()


    def mergeAddVoucherFromBill(self,billRuleItem, matchBillList):
        '''
        函数功能：将匹配规则的账单先合并成一条记账凭证，再添加到preview记账凭证表中
        :param billRuleItem:
        :param matchBillList:
        :return:
        '''
        pass
        totalValue=0.0 #总金额
        for matchBillListItem in matchBillList:
            totalValue = totalValue+ matchBillListItem.value



        if billRuleItem.property_increame_name == "":
            propertyIncreaseValue = 0.0
        else:
            propertyIncreaseValue = totalValue

        if billRuleItem.property_decrease_name == "":
            propertyDecreaseValue = 0.0
        else:
            propertyDecreaseValue = totalValue

        if billRuleItem.ownership_increase_name == "":
            ownershipIncreaseValue = 0.0
        else:
            ownershipIncreaseValue = totalValue

        if billRuleItem.ownership_decrease_name == "":
            ownershipDecreaseValue = 0.0
        else:
            ownershipDecreaseValue = totalValue

        tradeTime=setLastDayOfMonth(self.year, self.month)

        accountVoucher = AlipayVoucherPreviewAlchemy(tradeTime,
                                                     voucherNo="000",
                                                     summary=billRuleItem.summary,
                                                     propertyIncreaseName=billRuleItem.property_increame_name,
                                                     propertyIncreaseValue=propertyIncreaseValue,
                                                     propertyDecreaseName=billRuleItem.property_decrease_name,
                                                     propertyDecreaseValue=propertyDecreaseValue,
                                                     ownershipIncreaseName=billRuleItem.ownership_increase_name,
                                                     ownershipIncreaseValue=ownershipIncreaseValue,
                                                     ownershipDecreaseName=billRuleItem.ownership_decrease_name,
                                                     ownershipDecreaseValue=ownershipDecreaseValue,
                                                     voucherType=""
                                                     )

        accountVoucher.AddVoucherItem()
        accountVoucher.CommitVoucherData()

    def mergeAddVoucherFromNewBill(self,billRuleItem, matchBillList):
        '''
        函数功能：将匹配规则的账单先合并成一条记账凭证，再添加到preview记账凭证表中
        :param billRuleItem:
        :param matchBillList:
        :return:
        '''
        pass
        totalValue=0.0 #总金额
        for matchBillListItem in matchBillList:
            totalValue = totalValue+ matchBillListItem.value_first



        if billRuleItem.property_increame_name == "":
            propertyIncreaseValue = 0.0
        else:
            propertyIncreaseValue = totalValue

        if billRuleItem.property_decrease_name == "":
            propertyDecreaseValue = 0.0
        else:
            propertyDecreaseValue = totalValue

        if billRuleItem.ownership_increase_name == "":
            ownershipIncreaseValue = 0.0
        else:
            ownershipIncreaseValue = totalValue

        if billRuleItem.ownership_decrease_name == "":
            ownershipDecreaseValue = 0.0
        else:
            ownershipDecreaseValue = totalValue

        tradeTime=setLastDayOfMonth(self.year, self.month)

        accountVoucher = AlipayVoucherPreviewAlchemy(tradeTime,
                                                     voucherNo="000",
                                                     summary=billRuleItem.summary,
                                                     propertyIncreaseName=billRuleItem.property_increame_name,
                                                     propertyIncreaseValue=propertyIncreaseValue,
                                                     propertyDecreaseName=billRuleItem.property_decrease_name,
                                                     propertyDecreaseValue=propertyDecreaseValue,
                                                     ownershipIncreaseName=billRuleItem.ownership_increase_name,
                                                     ownershipIncreaseValue=ownershipIncreaseValue,
                                                     ownershipDecreaseName=billRuleItem.ownership_decrease_name,
                                                     ownershipDecreaseValue=ownershipDecreaseValue,
                                                     voucherType=""
                                                     )

        accountVoucher.AddVoucherItem()
        accountVoucher.CommitVoucherData()

    def loadParseBillRules(self):
        '''
        函数功能：加载账单解析规则
        :return:
        '''
        logger.debug("call loadParseBillRules function")
        billParseRegulationAlchemy = BillParseRegulationAlchemy()

        self.billParseRules = billParseRegulationAlchemy.SearchRegulationByBillType(BILL_TYPE_LIST[0])

        return

    def loadAlipayBillData(self, year, month):
        '''
        函数功能：加载指定月份的支付宝账单数据
        :param year:
        :param month:
        :return:
        '''
        logger.debug("call loadParseBillRules function")
        self.alipayBillAlchemy = AlipayBillAlchemy()
        self.alipayBillInforList = self.alipayBillAlchemy.SearchAlipayBillByMonth(year, month)

        return

    def loadNewAlipayBillData(self, year, month):
        '''
        函数功能：加载指定月份的支付宝账单数据
        :param year:
        :param month:
        :return:
        '''
        logger.debug("call loadParseBillRules function")
        self.alipayBillNewAlchemy = AlipayBillNewAlchemy()
        self.alipayBillInforList = self.alipayBillNewAlchemy.SearchAlipayBillByMonth(year, month)

        return
def onPreviewAlipayVoucher(year, month):
        '''
        函数功能：响应“支付宝记账凭证预览”事件
        :return:
        '''
        logger.debug("call onPreviewAlipayVoucher function")


        #如果支付宝记账凭证预览表中有数据，对数据进行清空
        accountingVoucherPreview = AlipayVoucherPreviewAlchemy()
        dataCount = accountingVoucherPreview.GetDataCount()
        if (dataCount!=0):
            accountingVoucherPreview.DelAllDataFromTable()


        #判断指定月份的记账凭证是否已经生成
        alipayVoucherAlchemy = AlipayVoucherAlchemy()
        alipayVoucherAlchemyResult = alipayVoucherAlchemy.SearchVoucherByMonth(year, month)
        if (len(alipayVoucherAlchemyResult)>0):
            #已经生成了支付宝记账凭证，无法重新生成支付宝记账凭证预览
            #QMessageBox.information(None, "【错误】", "当月支付宝记账凭证已经生成，生成支付宝预览记账凭证失败。", QMessageBox.Ok)
            return False

        #ParseAliPay.alipayBillToAccountVoucher(self.targetDate.year, self.targetDate.month)
        autoParseBill = AutoParseBill()
        autoParseBill.alipayBillToAccountVoucher(year, month)

        #QMessageBox.information(None, "提示", "完成预览支付宝记账凭证数据生成", QMessageBox.Ok)

        return True


def main():

    print("hello new year!")
    onPreviewAlipayVoucher(2024, 1)
    print("hello world!")


if __name__== "__main__":
    main()